import { IAuthInfo } from '~/types/sys/IAuthInfo'
import config from '~/config'
import { LoginService } from '~/service/login'
import router from '~/router'

class Store {
  keyToken: string = config.storeKeyPrefix + 'token'
  keyUser: string = config.storeKeyPrefix + 'user'

  setUser(authInfo: IAuthInfo) {
    localStorage.setItem(this.keyToken, authInfo.token)
    sessionStorage.setItem(this.keyUser, JSON.stringify(authInfo))
  }

  clear() {
    localStorage.clear()
    sessionStorage.clear()
  }

  getToken(): string | null {
    return localStorage.getItem(this.keyToken)
  }

  getUserLocal(): IAuthInfo | null {
    let authInfoJSON = sessionStorage.getItem(this.keyUser)
    if (authInfoJSON != null) {
      return JSON.parse(authInfoJSON) as IAuthInfo
    }
    return null
  }

  async getUser(): Promise<IAuthInfo> {
    return new Promise<IAuthInfo>((resolve) => {
      const token = localStorage.getItem(this.keyToken)
      if (token == null) {
        router.push({ path: '/login' })
        throw new Error('check login status fail,redirect to login')
      }
      let authInfoJSON = sessionStorage.getItem(this.keyUser)
      if (authInfoJSON != null) {
        resolve(JSON.parse(authInfoJSON) as IAuthInfo)
      }
      LoginService.info().then((authInfo) => {
        this.setUser(authInfo)
        resolve(authInfo)
      })
    })
  }
}

export default new Store()
